﻿Imports System.Xml.Serialization

<XmlRoot("List")> Public Class tagList
    Inherits tagBase

    <XmlAttribute("Type")> Public Type As Byte
    <XmlElement("Value")> Public Value As New List(Of tagBase)

    Public Sub New()

    End Sub

    Friend Sub New(ByVal str As System.IO.Stream)
        MyBase.New(str)

        Me.Type = ReadBytesFromStream(str, 1)(0)

        Dim Len As UInt32
        Len = BitConverter.ToUInt32(ReadBytesFromStream(str, 4).Reverse.ToArray, 0)


        For i = 0 To Len - 1
            Dim NewTag As tagBase
            Select Case Me.Type
                Case 1
                    NewTag = New tagByte
                    Dim b As Byte
                    b = ReadBytesFromStream(str, 1)(0)
                    If b < 128 Then
                        DirectCast(NewTag, tagByte).Value = CType(b, SByte)
                    Else
                        DirectCast(NewTag, tagByte).Value = CType(b - 256, SByte)
                    End If
                    Value.Add(NewTag)
                Case 2
                    NewTag = New tagShort
                    DirectCast(NewTag, tagShort).Value = BitConverter.ToInt16(ReadBytesFromStream(str, 2).Reverse.ToArray, 0)
                Case 3
                    NewTag = New tagInt
                    DirectCast(NewTag, tagInt).Value = BitConverter.ToInt32(ReadBytesFromStream(str, 4).Reverse.ToArray, 0)
                Case 4
                    NewTag = New tagLong
                    DirectCast(NewTag, tagLong).Value = BitConverter.ToInt64(ReadBytesFromStream(str, 8).Reverse.ToArray, 0)
                Case 5
                    NewTag = New tagFloat
                    DirectCast(NewTag, tagFloat).Value = BitConverter.ToSingle(ReadBytesFromStream(str, 4).Reverse.ToArray, 0)
                Case 6
                    NewTag = New tagDouble
                    DirectCast(NewTag, tagDouble).Value = BitConverter.ToDouble(ReadBytesFromStream(str, 8).Reverse.ToArray, 0)
                Case 10
                    NewTag = New tagCompound(str, True)
                Case Else
                    Throw New ApplicationException(String.Format("Tag-ID '{0}' is not valid for a list.", Me.Type))
            End Select
            Value.Add(NewTag)
        Next

    End Sub
End Class
